from django.db import models
from django.db import connection, transaction
from django.db import IntegrityError
from django.db import DatabaseError

from inv.utils.trace  import *

def lock_table(table):
   """Lock a particular table by providing its mapping Python Class
   """
   cursor = connection.cursor()
   cursor.execute("LOCK TABLES %s WRITE" % table._meta.db_table)
   cursor.fetchone()
        
def unlock_table():
    """Unlock all the tables are are locked so far
    """
    cursor = connection.cursor()
    cursor.execute("UNLOCK TABLES")
    cursor.fetchone()


def refine_col_val(typ, val, cls_id=None, met_id=None) :
   """
     This function returns the refined value that would be inserted into the 
     database tables
   
     Parameter :
        cls : class id
        met : meta id
        typ : type of the column
        val : User provide text
    
     Return Value : 
        None : If user has not provided any value
        CHAR, CHAR_UNIQ : 
            Trimmed white spaces and UPPER case letters
        TEXT : 
            Content exactly provided by user, no trimming no UPPER case
        INT, FLOAT, COMBO, DATE : 
            object of type int, float, combo_obj, date
    
     Exceptions :
        ValueError for float, int and date types
   """
   ret_val = None
   t = typ
   if t == "TEXT" :
      if val != "":
         ret_val = val
   else :
      v = ' '.join(val.upper().split())
      if v != "" : # Check if user has given all spaces
         if t == "INT" :
            ret_val = int(v) 
         elif t == "FLOAT" :
            ret_val = float(v)
         elif t == "CHAR" or t == "CHAR_UNIQ" :
            ret_val = v
         elif t == "COMBO" :
            ret_val, created = Combo_Content.objects.get_or_create(cls_id=cls_id, met_id=met_id, val=val)
            if created :
               ret_val.save()
         elif t == "DATE" :
            ret_val = datetime(int(val[:4]), int(val[4:6]), int(val[6:8]),
               int(val[8:10]), int(val[10:12]), int(val[12:14]))
#   D("MODEL : refine_col_val : Column Type = " + typ + ", Value = " + str(ret_val))
   return ret_val
